/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.controller;

import com.hsxxherp.key.uia.entity.SysApplicationVersion;
import com.hsxxherp.key.uia.service.ISysApplicationVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 应用版本管理控制器
 * 该控制器负责处理与应用版本管理相关的 HTTP 请求，
 * 包括创建、更新、删除、发布、回滚、开始测试、开始部署、标记部署状态等操作，
 * 以及根据应用 ID 获取已发布版本列表。
 */
@RestController
@RequestMapping("/api/versions")
public class SysApplicationVersionController {

    @Autowired
    private ISysApplicationVersionService versionService;

    /**
     * 创建应用版本
     * 处理 POST 请求，接收一个 SysApplicationVersion 对象作为请求体，
     * 调用服务层的 createVersion 方法创建新的应用版本。
     *
     * @param version 要创建的应用版本对象
     * @return 创建成功返回 201 Created 状态码和创建的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping
    public ResponseEntity<SysApplicationVersion> createVersion(@RequestBody SysApplicationVersion version) {
        try {
            SysApplicationVersion createdVersion = versionService.createVersion(version);
            if (createdVersion != null) {
                return new ResponseEntity<>(createdVersion, HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 更新应用版本
     * 处理 PUT 请求，接收一个 SysApplicationVersion 对象作为请求体，
     * 调用服务层的 updateVersion 方法更新应用版本。
     *
     * @param version 包含更新信息的应用版本对象
     * @return 更新成功返回 200 OK 状态码和更新后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PutMapping
    public ResponseEntity<SysApplicationVersion> updateVersion(@RequestBody SysApplicationVersion version) {
        try {
            SysApplicationVersion updatedVersion = versionService.updateVersion(version);
            if (updatedVersion != null) {
                return new ResponseEntity<>(updatedVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 删除应用版本
     * 处理 DELETE 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 deleteVersion 方法删除应用版本。
     *
     * @param versionId 要删除的应用版本的唯一标识
     * @return 删除成功返回 204 No Content 状态码，失败返回 500 Internal Server Error 状态码
     */
    @DeleteMapping("/{versionId}")
    public ResponseEntity<Void> deleteVersion(@PathVariable String versionId) {
        try {
            boolean success = versionService.deleteVersion(versionId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 发布应用版本
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 publishVersion 方法发布应用版本。
     *
     * @param versionId 要发布的应用版本的唯一标识
     * @return 发布成功返回 200 OK 状态码和发布后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/publish")
    public ResponseEntity<SysApplicationVersion> publishVersion(@PathVariable String versionId) {
        try {
            SysApplicationVersion publishedVersion = versionService.publishVersion(versionId);
            if (publishedVersion != null) {
                return new ResponseEntity<>(publishedVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 回滚应用版本
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 rollbackVersion 方法回滚应用版本。
     *
     * @param versionId 要回滚的应用版本的唯一标识
     * @return 回滚成功返回 200 OK 状态码和回滚到的目标版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/rollback")
    public ResponseEntity<SysApplicationVersion> rollbackVersion(@PathVariable String versionId) {
        try {
            SysApplicationVersion rolledBackVersion = versionService.rollbackVersion(versionId);
            if (rolledBackVersion != null) {
                return new ResponseEntity<>(rolledBackVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 开始应用版本测试
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 startTesting 方法开始应用版本测试。
     *
     * @param versionId 要开始测试的应用版本的唯一标识
     * @return 开始测试成功返回 200 OK 状态码和更新后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/start-testing")
    public ResponseEntity<SysApplicationVersion> startTesting(@PathVariable String versionId) {
        try {
            SysApplicationVersion testingVersion = versionService.startTesting(versionId);
            if (testingVersion != null) {
                return new ResponseEntity<>(testingVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 开始应用版本部署
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 startDeployment 方法开始应用版本部署。
     *
     * @param versionId 要开始部署的应用版本的唯一标识
     * @return 开始部署成功返回 200 OK 状态码和更新后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/start-deployment")
    public ResponseEntity<SysApplicationVersion> startDeployment(@PathVariable String versionId) {
        try {
            SysApplicationVersion deployingVersion = versionService.startDeployment(versionId);
            if (deployingVersion != null) {
                return new ResponseEntity<>(deployingVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 标记应用版本部署成功
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 markDeploymentSuccess 方法标记应用版本部署成功。
     *
     * @param versionId 要标记部署成功的应用版本的唯一标识
     * @return 标记成功返回 200 OK 状态码和更新后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/mark-deployment-success")
    public ResponseEntity<SysApplicationVersion> markDeploymentSuccess(@PathVariable String versionId) {
        try {
            SysApplicationVersion deployedVersion = versionService.markDeploymentSuccess(versionId);
            if (deployedVersion != null) {
                return new ResponseEntity<>(deployedVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 标记应用版本部署失败
     * 处理 POST 请求，接收版本 ID 作为路径参数，
     * 调用服务层的 markDeploymentFailed 方法标记应用版本部署失败。
     *
     * @param versionId 要标记部署失败的应用版本的唯一标识
     * @return 标记成功返回 200 OK 状态码和更新后的版本对象，失败返回 500 Internal Server Error 状态码
     */
    @PostMapping("/{versionId}/mark-deployment-failed")
    public ResponseEntity<SysApplicationVersion> markDeploymentFailed(@PathVariable String versionId) {
        try {
            SysApplicationVersion failedVersion = versionService.markDeploymentFailed(versionId);
            if (failedVersion != null) {
                return new ResponseEntity<>(failedVersion, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 根据应用 ID 获取已发布的应用版本列表
     * 处理 GET 请求，接收应用 ID 作为路径参数，
     * 调用服务层的 getPublishedVersionsByAppId 方法获取已发布的应用版本列表。
     *
     * @param appId 应用的唯一标识
     * @return 包含已发布应用版本列表的响应，成功返回 200 OK 状态码，失败返回 500 Internal Server Error 状态码
     */
    @GetMapping("/published/{appId}")
    public ResponseEntity<List<SysApplicationVersion>> getPublishedVersionsByAppId(@PathVariable String appId) {
        try {
            List<SysApplicationVersion> publishedVersions = versionService.getPublishedVersionsByAppId(appId);
            return new ResponseEntity<>(publishedVersions, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}